import path from 'node:path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import tsconfigPaths from 'vite-tsconfig-paths'
import externalGlobals from 'rollup-plugin-external-globals'
import copy from 'rollup-plugin-copy'
import { buildConfig } from '../../../../build/platform/index'
import { createVitePlugins } from '../../../../build/platform/vitePlugins.mjs'
import { CONFIG_INFO } from '../config.mjs'

export default defineConfig(config => {
  const isProd = config.mode === 'production'
  return {
    base: './',
    plugins: [
      ...createVitePlugins(),
      copy({
        targets: [{ src: ['../icon.svg'], dest: '../dist' }]
      }),
      tsconfigPaths()
    ],

    ...(isProd && { define: { 'process.env.NODE_ENV': '"production"' } }),

    build: {
      lib: buildConfig(CONFIG_INFO),
      outDir: path.join(__dirname, '../dist/vue/edition'),
      rollupOptions: {
        output: {
          assetFileNames: assetInfo => {
            if (assetInfo.name?.endsWith('.css')) {
              return 'main.css'
            }
            return assetInfo.name || ''
          }
        },
        external: ['vue', 'vue-demi'],
        plugins: [
          externalGlobals({
            vue: 'Vue',
            'vue-demi': 'VueDemi',
            '@formily/vue': 'FormilyVue'
          })
        ]
      }
    },

    worker: {
      // 支持worker tsconfig-paths解析
      plugins: () => [tsconfigPaths()]
    },

    resolve: {
      dedupe: ['vue', 'vue-demi']
    }
  }
})
